package com.gov.dna.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    /**
     * 在controller里面内容执行之前，校验一些参数不匹配啊，Get post方法不对啊之类的
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public void handleException(HttpServletRequest req, Exception e) {
        // 验证全局异常
        if (e instanceof BindException) {
            String errmsg = "";
            for (FieldError error : ((BindException) e).getBindingResult().getFieldErrors()) {
                errmsg = errmsg + error.getDefaultMessage() + "  ";
            }
            log.info("BindException");
            // 验证-字符串长度验证
        } else if (e instanceof MethodArgumentNotValidException) {
            String errmsg = "";
            for (FieldError error : ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors()) {
                errmsg = errmsg + error.getDefaultMessage() + "  ";
            }
            log.info(errmsg);
        } else if (e instanceof NumberFormatException) {
            log.info("您的数据格式有问题，请正确处理！");
        } else if (e instanceof RuntimeException) {
            RuntimeException re = (RuntimeException) e;
            log.info(re.getMessage());
        } else if (e instanceof HttpMessageNotReadableException) {
            HttpMessageNotReadableException re = (HttpMessageNotReadableException) e;
            log.info(re.getMessage());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            log.info("您的请求方式有问题，请正确处理！");
        } else {
            log.info("您的数据异常，请正确处理！");
        }


    }


}
